﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.Text.RegularExpressions;

using Kaixin001.Common;
using KxzzEntity.UsersEntity;
using Entity.MsgEntity;
using Kaixin001.StringUtil;


namespace Kaixin001.Msg
{
    public class MsgHelper
    {
        #region 变量
        private string baseUrl = "http://www.kaixin001.com";
        private string msgBaseUrl = "http://www.kaixin001.com/msg/";
        private string msgInboxUrl = "http://www.kaixin001.com/msg/inbox.php?t=";
        private string msgGbookUrl = "http://www.kaixin001.com/comment/uindex.php?t=";
        private string msgPlUrl = "http://www.kaixin001.com/comment/?t=";
        private string msgSysUrl = "http://www.kaixin001.com/msg/sys.php?t=";
        private string msgGbookReplyUrl = "http://www.kaixin001.com/comment/usend.php?t=";
        private string msgPlReplyUrl = "http://www.kaixin001.com/comment/send.php?t=";
        private string msgPostUrl = "http://www.kaixin001.com/msg/post.php";

        private string rcode = string.Empty;
        private string r;
        private Random ran = new Random();
        Kaixin001Http kaixin001Http;
        #endregion

        #region 属性
        public string RandomValue
        {
            get
            {
                this.r = this.ran.NextDouble().ToString();
                if (this.r.Length < 0x12)
                {
                    this.r = this.r + this.ran.Next(100);
                }
                return this.r;
            }
        }
        #endregion

        #region 构造函数
        public MsgHelper(Kaixin001Http kaixin001Http)
        {
            this.kaixin001Http = kaixin001Http;
        }
        #endregion

        /// <summary>
        /// 更新用户消息条数
        /// </summary>
        /// <param name="user"></param>
        /// <returns></returns>
        public UserInfoEntity GetMsgCount(UserInfoEntity user)
        {
            WebResponse webResponse = kaixin001Http.doGetRetry(this.msgBaseUrl);

            string resultHtml = this.kaixin001Http.GetHtml(webResponse);

            if (resultHtml.Contains("消息中心 - 开心网"))
            {
                //匹配短消息数量
                Regex regex = new Regex("id=body_msg_num>(?<count>\\d{1,9})条新</a>");
                MatchCollection matchs = regex.Matches(resultHtml);

                matchs = regex.Matches(resultHtml);
                user.MessageCount = int.Parse(matchs[0].Groups["count"].Value);

                //匹配系统消息数量
                regex = new Regex("id=body_sysmsg_num>(?<count>\\d{1,9})条新</a>");
                matchs = regex.Matches(resultHtml);
                user.SysMessageCount = int.Parse(matchs[0].Groups["count"].Value); ;

                //匹配留言数量
                regex = new Regex("id=body_bbs_num>(?<count>\\d{1,9})条新</a>");
                matchs = regex.Matches(resultHtml);
                user.GuestBookCount = int.Parse(matchs[0].Groups["count"].Value);

                //匹配评论数量
                regex = new Regex("id=body_reply_num>(?<count>\\d{1,9})条新");
                matchs = regex.Matches(resultHtml);
                user.CommentCount = int.Parse(matchs[0].Groups["count"].Value);

            }
            GetMessage(user);
            return user;
        }

        /// <summary>
        /// 获取消息
        /// </summary>
        /// <param name="user"></param>
        /// <returns></returns>
        public List<MessageEntity> GetMessage(UserInfoEntity user)
        {
            List<MessageEntity> listMessage = new List<MessageEntity>();

            this.rcode = this.RandomValue + "_" + DateTime.Now.Ticks.ToString();
            string resultHtml = "";
            string strUrl = string.Format(this.msgInboxUrl + "{0}", this.rcode);

            Regex regex =  new Regex("href=\"(?<messageUrl>.+)\"\\s+title=\"查看该消息\">");
            //regex = new Regex("unread.gif(?s)(?i)<div><a\\s+class=\"sl\"\\s+(?<messageUrl>.+)查看该消息");
            MatchCollection matchs = regex.Matches(resultHtml);

            resultHtml = this.kaixin001Http.GetHtml(this.kaixin001Http.doGetRetry(strUrl));
            matchs = regex.Matches(resultHtml);

            foreach (Match match in matchs)
            {
                MessageEntity messageEntity = new MessageEntity();
                MatchCollection matchInner;

                messageEntity.ThreadUrl = this.baseUrl + match.Groups["messageUrl"].Value;

                regex = new Regex("style=\"margin-top:50px;margin-left:15px;\">(?<FromUser>.+)和(?<ToUser>.+)之间的私密对话</b></div>");
                resultHtml = this.kaixin001Http.GetHtml(this.kaixin001Http.doGetRetry(messageEntity.ThreadUrl));
                matchInner = regex.Matches(messageEntity.ThreadUrl);
                if (matchInner.Count > 0)
                {
                    messageEntity.FromUser = matchInner[0].Groups["FromUser"].Value;
                    messageEntity.ToUser = matchInner[0].Groups["ToUser"].Value;
                }

                resultHtml = StringHelper.GetMidString(resultHtml, "之间的私密对话", "<div class=\"dxx_sc\">");
                resultHtml = resultHtml.Replace("<div class=\"dxx4\"><div class=\"l50_s\">", "@");

                string[] strHtml = resultHtml.Split('@');
                foreach (string str in strHtml)
                {
                    messageEntity = new MessageEntity();

                    regex = new Regex("<a href=\"/home/\\?uid=(?<uid>\\d+)\" class=\"sl\".+>(?<user>.+)</a><br /><span class=\"c9\">");
                    matchInner = regex.Matches(str);
                    if (matchInner.Count > 0)
                    {
                        messageEntity.SendUid = matchs[0].Groups["uid"].Value;
                        messageEntity.SendUser = matchs[0].Groups["user"].Value;
                    }

                    regex = new Regex("</a><br /><span class=\"c9\">(?<time>.+)</span>");
                    matchInner = regex.Matches(str);
                    if (matchInner.Count > 0)
                        messageEntity.SendTime = matchs[0].Groups["time"].Value;

                    string strMessage = StringHelper.GetMidString(str, "<div class=\"dxx_mr4\" style=\"width:570px;\">", "</div>");
                    if (!string.IsNullOrEmpty(strMessage))
                        messageEntity.Message = StringHelper.DelHtmlString(strMessage);

                    if (!string.IsNullOrEmpty(messageEntity.Message))
                    {
                        listMessage.Add(messageEntity);
                    }
                }
            }

            #region 截取短信
            #endregion

            return listMessage;
        }

        /// <summary>
        /// 发送消息
        /// </summary>
        /// <param name="uids"></param>
        /// <param name="message"></param>
        /// <param name="textType"></param>
        /// <returns></returns>
        public bool SendMessage(string uids, string message, string textType)
        {
            bool result = false;
            this.rcode = this.RandomValue + "_" + DateTime.Now.Ticks.ToString();

            string postData = string.Format("attachment_random=&attachment_cancel=&uids={0}&rcode={1}&content={2}&texttype={3}&code=",
                uids,
                this.rcode,
                message,
                textType);

            string html = this.kaixin001Http.GetHtml(this.kaixin001Http.doPostRetry(msgPostUrl, postData));

            if (html != null && html.Length > 0 && StringHelper.DelHtmlString(html).Contains( StringHelper.DelHtmlString(message)))
            {
                result = true;
            }

            return result;
        }
    }
}
